package com.ruoyi.system.controller;

import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.AppFile;
import com.ruoyi.system.service.IAppFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.util.UriUtils;

/**
 * App 管理Controller
 *
 * @author ruoyi
 * @date 2024-05-01
 */
@RestController
@RequestMapping("/system/file")
public class AppFileController extends BaseController
{
    @Autowired
    private IAppFileService appFileService;

    /**
     * 查询App 管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppFile appFile)
    {
        startPage();
        List<AppFile> list = appFileService.selectAppFileList(appFile);
        return getDataTable(list);
    }
    @Anonymous
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("fileName") String fileName) throws Exception {
        String outputFilePath = (RuoYiConfig.getDownloadPath() +fileName).replaceAll("/download/profile","");
        Path path = Paths.get(outputFilePath);
        Resource resource = null;
        try {
            resource = new UrlResource(path.toUri());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // 设置请求头参数以及下载的文件名称,中文名称转义防止乱码
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName+";filename*=UTF-8''" +
                UriUtils.encode(fileName, StandardCharsets.UTF_8));
        //
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("download-filename", fileName);
        // 返回响应实体，包含文件内容和响应头
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

    @Anonymous
    @GetMapping("/oneApp")
    public  List<AppFile> oneApp(AppFile appFile)
    {
        return appFileService.selectAppFileList(appFile);
    }

    /**
     * 导出App 管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "App 管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppFile appFile)
    {
        List<AppFile> list = appFileService.selectAppFileList(appFile);
        ExcelUtil<AppFile> util = new ExcelUtil<AppFile>(AppFile.class);
        util.exportExcel(response, list, "App 管理数据");
    }

    /**
     * 获取App 管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(appFileService.selectAppFileById(id));
    }

    /**
     * 新增App 管理
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "App 管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppFile appFile)
    {
        return toAjax(appFileService.insertAppFile(appFile));
    }

    /**
     * 修改App 管理
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "App 管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppFile appFile)
    {
        return toAjax(appFileService.updateAppFile(appFile));
    }

    /**
     * 删除App 管理
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "App 管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(appFileService.deleteAppFileByIds(ids));
    }
}
